<?
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Disable database connection
$_GLOBAL['no-db-con'] = true;
// Don't load configuration
$_GLOBAL['no-config'] = true;

// Load bootstrap.php so we can use
// user creation functions
require('../bootstrap.php');

$config = $_SESSION['config'];
$db_config = $_SESSION['db'];
$use_rewrite = ($_SESSION['use_rewrite'] == true) ? 'true' : 'false';

$config_file_content = '<? 
define("DB_HOST", "{host}");
define("DB_USER", "{user}");
define("DB_PASS", "{pass}");
define("DB_NAME", "{name}");
define("DB_TABLE_PREFIX", "{prefix}");
define("USE_MOD_REWRITE", {rewrite});
?>';

$config_file_content = str_replace('{host}', $db_config['db_host'], $config_file_content);
$config_file_content = str_replace('{user}', $db_config['db_user'], $config_file_content);
$config_file_content = str_replace('{pass}', $db_config['db_pass'], $config_file_content);
$config_file_content = str_replace('{name}', $db_config['db_name'], $config_file_content);
$config_file_content = str_replace('{prefix}', $db_config['db_prefix'], $config_file_content);
$config_file_content = str_replace('{rewrite}', $use_rewrite, $config_file_content);

$config_file_name = '../configuration.php';
$config_file_handle = fopen($config_file_name, 'w') or die('Can\'t create configuration.php');
fwrite($config_file_handle, $config_file_content);
fclose($config_file_handle);

// Now configuration file is created, so load it
require('../configuration.php');

assert(defined('DB_HOST'));
assert(defined('DB_USER'));
assert(defined('DB_PASS'));
assert(defined('DB_NAME'));
assert(defined('DB_TABLE_PREFIX'));

$prefix = $db_config['db_prefix'];
$config_table = $prefix . '_SiteConfig';
$pages_table = $prefix . '_Pages';
$authors_table = $prefix . '_Authors';

$site_config_sql = "
CREATE TABLE `$config_table` (
  `site_name` VARCHAR(255) NOT NULL,
  `site_index` VARCHAR(255) NOT NULL,
  `style_header_color` VARCHAR(20),
  `style_menu_color` VARCHAR(20),
  `template` VARCHAR(255)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
";

$authors_sql = "
CREATE TABLE `$authors_table` (
  `id` int(11) NOT NULL auto_increment,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password_hash` varchar(255) NOT NULL,
  `password_salt` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
";

$pages_sql = "
CREATE TABLE `$pages_table` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL,
  `text` text NOT NULL,
  `updated_at` timestamp NOT NULL default CURRENT_TIMESTAMP,
  `author_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `index` int(11) NOT NULL default '0',
  `viewed` TINYINT(1) NOT NULL default true,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
";

$errors = array();
$install_started = true;
$install_completed = false;

// Check connection to database
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$link) {
	$errors[] = "Database fejl, kan ikke forbinde til databasen";
}
$db = mysql_select_db(DB_NAME);
if (!$db) {
	$errors[] = "Database fejl, kan ikke finde databasen";
}

// Create tables
mysql_query("DROP TABLE IF EXISTS `$config_table`") or die(mysql_error());
mysql_query($site_config_sql) or die(mysql_error());

mysql_query("DROP TABLE IF EXISTS `$authors_table`") or die(mysql_error());
mysql_query($authors_sql) or die(mysql_error());

mysql_query("DROP TABLE IF EXISTS `$pages_table`") or die(mysql_error());
mysql_query($pages_sql) or die(mysql_error());

// Save configuration settings
$q = "INSERT INTO $config_table (site_name, site_index) VALUES ('$config[site_name]', '$config[site_index]')";
$r = mysql_query($q) or die(mysql_error());

$salt = generate_salt();
$password = encrypt_password($config['password'], $salt);

// Create administration user
$str = "INSERT INTO $authors_table
		(username, first_name, last_name, password_hash, password_salt) ".
		"VALUES ('".$config['username']."','".$config['first_name']."','".$config['last_name']."',".
		"'".$password."', '".$salt."')";

$res = mysql_query($str) or die(mysql_error());


// Find administration user
$res = mysql_query("SELECT * FROM $authors_table 
		WHERE username = '$config[username]'") or die(mysql_error());		
$author = mysql_fetch_array($res);


// Create index page
$name_title = $config['site_index'];
$text = "Velkommen til $config[site_name] !";
$res = mysql_query("INSERT INTO $pages_table (title, `text`, author_id, name, `index`) 
	VALUES ('$name_title', '$text', $author[id], '$name_title', 0)") or die(mysql_error());

$install_completed = true;

?>

<html>
	<head>
		<title>Installation af KomitCMS</title>
		<meta http-equiv="content-type" content="text/html;charset=utf-8" />
		<meta http-equiv="Content-Style-Type" content="text/css" />
		<link rel="stylesheet" type="text/css" href="../stylesheet/style.css" />
		<link rel="stylesheet" type="text/css" href="../stylesheet/install.css" />
	</head>
	
	<body style="margin: 0">
		<div id="control">
			<button onclick="//parent.previousStep()">Forige</button>
		</div>
		<h2 class="page-header">Afslut</h2>
		<div id="description"></div>
		<div id="step" style="margin-top: 10px; padding-top: 10px;">
			<? if ($install_completed) { ?>
				<div style="padding: 10px; border: 1px solid #CCC; background: #EEE">
					<b>Installationen er fuldført!</b>
					<br/><br/>
					<button onclick="parent.location.href='../'">Gå til forsiden</button>
					<button onclick="parent.location.herf='../admin'">Gå til admin-panelet</button>
				</div>
			
			<? } ?>
		</div>
	</body>
</html>